package org.example.word.process;


import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

public class WordTemplateProcessor {
    public static ByteArrayOutputStream  processTemplate(String templatePath, Map<String, String> replacements) throws Exception {
         // Load template from resources
        try (InputStream templateStream = Files.newInputStream(Paths.get(templatePath));
             XWPFDocument document = new XWPFDocument(templateStream)) {

            // Replace placeholders in paragraphs
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                replaceText(paragraph, replacements);
            }

            // Replace placeholders in tables
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        for (XWPFParagraph paragraph : cell.getParagraphs()) {
                            replaceText(paragraph, replacements);
                        }
                    }
                }
            }

            // 保存修改后的 Word 文档到本地
//            String outputWordPath = "C:\\Users\\Administrator\\IdeaProjects\\suanming\\src\\main\\resources\\output.docx";
//            FileOutputStream out = new FileOutputStream(outputWordPath);
            ByteArrayOutputStream wordOutputStream = new ByteArrayOutputStream();
            document.write(wordOutputStream);
            document.close();

            return wordOutputStream;
        }
    }

    private static  void replaceText(XWPFParagraph paragraph, Map<String, String> replacements) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            if (text != null) {
                for (Map.Entry<String, String> entry : replacements.entrySet()) {
                    text = text.replace("${" + entry.getKey() + "}", entry.getValue());
                }
                // Replace remaining placeholders with empty string
                for (String key : replacements.keySet()) {
                    text = text.replace("${" + key + "}", ""); // Replace unmatched placeholders
                }
                run.setText(text, 0);
            }
        }
    }

//    private static void convertToPdf(String wordPath, ByteArrayOutputStream pdfOutputStream) throws IOException {
//        try {
//            // 读取 Word 文档
//            FileInputStream fis = new FileInputStream(wordPath);
//            XWPFDocument document = new XWPFDocument(fis);
//
//            // 创建 PDF 文档
//            Document pdfDoc = new Document();
//            PdfWriter.getInstance(pdfDoc, new FileOutputStream("C:\\Users\\Administrator\\IdeaProjects\\suanming\\src\\main\\resources\\output.pdf"));
//            pdfDoc.open();
//
//            // 遍历 Word 文档的段落
//            for (XWPFParagraph paragraph : document.getParagraphs()) {
//                StringBuilder text = new StringBuilder();
//                // 遍历段落中的文本运行对象
//                for (XWPFRun run : paragraph.getRuns()) {
//                    text.append(run.getText(0));
//                }
//                // 将段落文本添加到 PDF 文档中
//                Paragraph pdfParagraph = new Paragraph(text.toString());
//                pdfDoc.add(pdfParagraph);
//            }

//            // 关闭文档和流
//            pdfDoc.close();
//            document.close();
//            fis.close();
//
//            System.out.println("Word 转 PDF 成功！");
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("Word 转 PDF 失败：" + e.getMessage());
//        }
//    }
}